package com.yjf.mydockerCompose.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class mydockercomposeAspect {

    @Autowired
    private HttpServletRequest request;


    @Pointcut("execution (* com.yjf.mydockerCompose.controller..*.*(..))")
    public void logPoinCut(){
    }

    @Around("logPoinCut()")
    public Object doBefore(ProceedingJoinPoint joinPoint){
        String ipAddress = getClientIp(request);
        String methodName = joinPoint.getSignature().getDeclaringTypeName()+" "+joinPoint.getSignature().getName();
        log.info(ipAddress+" 开始请求 "+methodName);

        try{
            return joinPoint.proceed();
        }catch (Exception e){
            log.error(e.getMessage());
        } catch (Throwable throwable) {
            log.error(throwable.getMessage());
        }finally {
            log.info(ipAddress+" 结束请求");
        }
        return null;
    }

    public String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


}
